package com.liy.teaching.config;

import com.liy.teaching.service.ProductService;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfiguration {

    /**
     * 预计要插入多少数据
     */
    private static int size = 100000; // 十万


    /**
     * 期望的误判率
     */
    private static double fpp = 0.001;


    @Value("${spring.redis.host}")
    private String redistHost;

    @Value("${spring.redis.port}")
    private Integer redistPort;


    @Autowired
    private ProductService productService;  // 商品服务


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        // 创建 RedisTemplate 对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        // 设置开启事务支持
        template.setEnableTransactionSupport(true);

        // 设置 RedisConnection 工厂。 它就是实现多种 Java Redis 客户端接入的秘密工厂
        template.setConnectionFactory(factory);

        // 使用 String 序列化方式，序列化 KEY 。
        template.setKeySerializer(RedisSerializer.string());

        // 使用 JSON 序列化方式（库是 Jackson ），序列化 VALUE 。
        template.setValueSerializer(RedisSerializer.json());

        return template;
    }


    /**
     * RedissonClient 注册
     */
    @Bean
    public RedissonClient redissonClient(){
        String redisAddress = "redis://"+redistHost+ ":"+redistPort;

        Config config = new Config();
        config.useSingleServer().setAddress(redisAddress);
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }


    /**
     * 布隆过滤器
     *
     */
    @Bean
    public RBloomFilter redisBloomFilter(){

        // 创建RedisBloomFilter
        RBloomFilter<String> redisBloomFilter = redissonClient().getBloomFilter("productBloomFilter04");

        //初始化布隆过滤器：预计元素为10000L ( 十万), 误差率为 0.001
        redisBloomFilter.tryInit(size, fpp);



        return redisBloomFilter;
    }

}
